package sg.edu.nus.iss.cats.action;

import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.commons.beanutils.*;

import sg.edu.nus.iss.cats.form.*;
import sg.edu.nus.iss.cats.model.*;
import sg.edu.nus.iss.cats.controller.*;
import sg.edu.nus.iss.cats.exception.*;

public class CourseSubmitAction extends Action {

    /**
      * The submit method receives the new course details from the
      * courseForm, creates a Course object
      * from the form bean and sends it for an insert in the DB
      */
    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response)
                         throws CourseCreateException {

        System.out.println("CourseSubmitAction: submit()");

        // Get the submitter id (current user's employees id)

        HttpSession session = request.getSession();
        UserSession userSession =
            (UserSession) session.getAttribute("USERSESSION");
        String submitterId = userSession.getEmployee().getEmployeeId();

        // Ask the database for a new unique application id for this record

        CourseManager caBD = new CourseManager();
        int appId = caBD.getNewCourseId();

        /************************************************
           WORKSHOP W07_FORMS
           create a new Course and initialise it with the content of the form bean
           ************************************************
        **/
        CourseForm caForm = (CourseForm) form;
        Course ca = new Course();
        try {
            // Transfer the properties, converting where necessary
            BeanUtils.copyProperties(ca, caForm);
        } catch (Exception e) {
            throw new CourseCreateException(
                "Could not create the Course Application: " + e);
        }

        ca.setCourseId(appId);
        ca.setEmployeeId(submitterId);
        ca.setStatus(Course.SUBMITTED);

        // Enter the new course application in the db
        caBD.insertCourse(ca, submitterId, "Original submission");

        System.out.println("CourseSubmitAction successful");
        return mapping.findForward("employeeDefault");
    }
}
